<?php


namespace App\Console\Commands;


use App\Models\FilmTypeMaster;
use App\Models\WarrantyToVehicleCoverage;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UpdateWarrantyTime extends Command
{

    protected $signature = 'warranty:update-time {startDate}';

    protected $description = '更新质保时间';

    public function handle()
    {
        $startDate = $this->argument('startDate');
        if (empty($startDate)) {
            $startDate = "2024-01-01";
        }
        $count = 500;
        $page = 0;
        while ($count == 500){
            echo $page."\n";
            $count = $this->updateWarrantyTime($page,$startDate);
            $page ++;
        }
    }

    public function updateWarrantyTime($page,$startDate){
        $warrantyList = DB::table("warranty")->where("approved", 1)
            ->where('created_at', '>', $startDate)
            ->select("id", "installation_date")
            ->offset($page * 500)
            ->limit(500)
            ->get();
        if(empty($warrantyList) || $warrantyList->isEmpty()){
            return 0;
        }
        foreach ($warrantyList as $item){
            $coverages = WarrantyToVehicleCoverage::where('warranty_id', $item->id)
                ->get();
            foreach ($coverages as $coverage){
                $filmType = FilmTypeMaster::where('id',$coverage->film_type_id)->first();
                if (!empty($filmType) && !empty($filmType->warranty_days) && !empty($item->installation_date)){
                    $starTime =  strtotime($item->installation_date);
                    $endTime = strtotime("+$filmType->warranty_days days", $starTime);
                    $coverage->start_time = $starTime;
                    $coverage->end_time= $endTime;
                    $coverage->save();
                }
            }
            echo  $item->id."\n";
        }
        return count($warrantyList);
    }
}